﻿#region 版权信息
// ------------------------------------------------------------------------------
// Copyright: (c) 2029  耍嗨科技（成都）有限公司 - Amm
// 项目名称：$SOLUTION/$.Amm.Common
// 文件名称：EnumExtensions.cs
// 创建时间：2020093011:12
// 更改时间：2020093011:12
//  ------------------------------------------------------------------------------
#endregion

using Colorful.Furniture.CommonDto;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace Colorful.Furniture.Extensions
{
    public static class EnumExtensions
    {
        /// <summary>
        ///  转换成描述
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string ToDescription(this System.Enum item)
        {
            string name = item.ToString();
            var desc = item.GetType().GetField(name)?.GetCustomAttribute<DescriptionAttribute>();
            return desc?.Description ?? name;
        }

        /// <summary>
        ///  转换成数字字符串
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string ToValueIntString(this System.Enum item)
        {
            try
            {
                return item == null
                    ? string.Empty
                    : Convert.ToInt32(item).ToString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                return string.Empty;
            }
        }

        public static long ToInt64(this System.Enum item)
        {
            return Convert.ToInt64(item);
        }

        public static List<OptionOutputDto> ToList(this System.Enum value, bool ignoreUnKnown = false)
        {
            var enumType = value.GetType();

            if (!enumType.IsEnum)
                return null;

            return System.Enum.GetValues(enumType).Cast<System.Enum>()
                .Where(m => !ignoreUnKnown || !m.ToString().Equals("UnKnown")).Select(x => new OptionOutputDto
                {
                    Label = x.ToDescription(),
                    Value = x
                }).ToList();
        }

        public static List<OptionOutputDto> ToList<T>(bool ignoreUnKnown = false)
        {
            var enumType = typeof(T);

            if (!enumType.IsEnum)
                return null;

            return System.Enum.GetValues(enumType).Cast<System.Enum>()
                .Where(m => !ignoreUnKnown || !m.ToString().Equals("UnKnown")).Select(x => new OptionOutputDto
                {
                    Label = x.ToDescription(),
                    Value = x
                }).ToList();
        }
    }
}